package org.ethan.practice.no_select_tab;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import org.ethan.practice.R;

import java.util.ArrayList;

/**
 * @ClassName: SelectTabAct
 * @Desc:
 * @Author: ethan
 * @CreateDate: 2019/9/23 14:41
 */
public class SelectTabAct extends AppCompatActivity {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private TabFragmentPagerAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_select_tab);
        mTabLayout = findViewById(R.id.tab_layout);
        mViewPager = findViewById(R.id.view_pager);

        ArrayList<Fragment> fragments = new ArrayList<>();
        ArrayList<String> mTitles = new ArrayList<>();
        for (int index = 0; index < 10;index ++) {
            TabFragment fragment = new TabFragment();
            fragments.add(fragment);
            mTitles.add("index:" +index);
        }

        mAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(),fragments);
        mViewPager.setAdapter(mAdapter);
//        mTabLayout.setupWithViewPager(mViewPager);

        mTabLayout.removeAllTabs();
        for (int index = 0;index<mTitles.size();index++) {
            View tabItemView = LayoutInflater.from(this).inflate(R.layout.item_tab, null);
            TextView tvTitle = tabItemView.findViewById(R.id.tv_title);
            tvTitle.setSelected(false);
            tvTitle.setTextColor(getResources().getColor(R.color.color_1B1828));
            tabItemView.setSelected(false);
            tvTitle.setText(mTitles.get(index));
            TabLayout.Tab tab = mTabLayout.newTab().setCustomView(tabItemView);
            mTabLayout.addTab(tab,false);
        }

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mViewPager.setCurrentItem(tab.getPosition(),true);
                TextView tvTitle = tab.getCustomView().findViewById(R.id.tv_title);
                tvTitle.setTextColor(getResources().getColor(R.color.color_1B1828));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tvTitle = tab.getCustomView().findViewById(R.id.tv_title);
                tvTitle.setTextColor(getResources().getColor(R.color.color_b46e50));
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }


}
